package com.study.sgu.hsp.bio;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/26 22:13
 */
public class BIOServer {
    /**
     * bio 传统 javaio 编程
     */


    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket socket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while (true) {
            //监听，等待客户端连接
            final Socket accept = socket.accept();
            System.out.println("连接到一个客户端了");

            //创建一个线程，与之通信
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    //和客户端通信
                    handler(accept);
                }
            });
        }
    }

    // 通信方法，和客户端通信
    public static void handler(Socket socket) {
        try {
            System.out.println("线程ID" + Thread.currentThread().getId() + "线程名字" + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //通过sockt获取输入流
            InputStream inputStream = socket.getInputStream();
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    //客户端发送的数据
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(socket);
        }
    }
}
